# 面部检测
import requests
import json

subscription_key = "22860f2ec4fa40668703f86a97b571b6"
assert subscription_key

face_api_url = "https://chick.cognitiveservices.azure.com/face/v1.0/detect"

# 请求正文
image_url = "https://pic3.zhimg.com/v2-ad22f53d179d317b0195fe824874e6d4_r.jpg"

headers = {'Ocp-Apim-Subscription-Key': subscription_key}

# 请求参数
params = {
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
}

response = requests.post(face_api_url, params=params,
                         headers=headers, json={"url": image_url})
# json.dumps 将json--->bytes
json.dumps(response.json())

# 2.json转译
results = response.json()
results

# 3.pandas 数据表格化
import pandas as pd
df_face = pd.json_normalize(results)
df_face

2. create facelist创建人脸列表

import requests
# 1、create  列表
# faceListId
faceListId =  "chick_22"#学生填写
create_facelists_url = "https://chick.cognitiveservices.azure.com/face/v1.0/facelists/{}" #学生填写
subscription_key = "22860f2ec4fa40668703f86a97b571b6"#学生填写
assert subscription_key

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': subscription_key,
}
data = {
    "name":"网新周四下午课",
    "userDate":"55人,30女,25男",
    "recognitionModel":"recognition_03"
# 学生填写
    
}
r_create = requests.put(create_facelists_url.format(faceListId), headers=headers, json=data)
r_create.content
# b''

r_create
# <Response [200]>
r_create.content
# b''
# 创建成功

# 2. get facelist获取人脸列表
# 检查你的facelist的信息
get_facelist_url = "https://chick.cognitiveservices.azure.com/face/v1.0/facelists/chick_22"
r_get_facelist = requests.get(get_facelist_url,headers=headers)

# r_get_facelist.json()
# {'persistedFaces': [], 'faceListId': 'chick_01', 'name': '网新周四下午课'}

# 3.add face 增加一张脸
add_face_url = "https://chick.cognitiveservices.azure.com/face/v1.0/facelists/chick_22/persistedfaces"

assert subscription_key
headers = {
# 请求头
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': subscription_key,
}
img_url = "https://pic3.zhimg.com/v2-ad22f53d179d317b0195fe824874e6d4_r.jpg"

params_add_face={
    "userData":"ji"
}

# 发送请求
r_add_face = requests.post(add_face_url,headers=headers,params=params_add_face,json={"url":img_url})
# r_add_face.status_code
# 200

# 检查你的facelist的信息
get_facelist_url = "https://chick.cognitiveservices.azure.com/face/v1.0/facelists/chick_22"
r_get_facelist = requests.get(get_facelist_url,headers=headers)
r_get_facelist.json()

 {'persistedFaces': [{'persistedFaceId': 
 'f2113ad2-cce9-4cb5-887b-52441ac4d7e9',
  'userData': 'ji'},
 {'persistedFaceId': 
 '35c6ff4c-d882-4889-866f-cd4d1904899b',
 'userData': 'ji'}],
'faceListId': 'chick_22',
'name': '网新周四下午课'}

# 4.封装成函数方便多次使用
def AddFace(img_url=str,userData=str):
    add_face_url ="https://chick.cognitiveservices.azure.com/face/v1.0/facelists/chick_22/persistedfaces"
    assert subscription_key
    headers = {
    #请求头
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': subscription_key,
    }
    img_url = img_url

    params_add_face={
        "userData":userData
    }
    r_add_face = requests.post(add_face_url.format(faceListId),headers=headers,params=params_add_face,json={"url":img_url})
    return r_add_face.status_code#返回出状态码
AddFace("http://huangjieqi.gitee.io/picture_storage/Autumnhui.jpg","丘天惠")
AddFace("http://huangjieqi.gitee.io/picture_storage/L-Tony-info.jpg","林嘉茵")
AddFace("http://huangjieqi.gitee.io/picture_storage/TLINGP.jpg","汤玲萍")
AddFace("http://huangjieqi.gitee.io/picture_storage/WenYanZeng.jpg","曾雯燕")
AddFace("http://huangjieqi.gitee.io/picture_storage/XIEIC.jpg","谢依希")
AddFace("http://huangjieqi.gitee.io/picture_storage/YuecongYang.png","杨悦聪")
AddFace("http://huangjieqi.gitee.io/picture_storage/Zoezhouyu.jpg","周雨")
AddFace("http://huangjieqi.gitee.io/picture_storage/crayon-heimi.jpg","刘瑜鹏")
AddFace("http://huangjieqi.gitee.io/picture_storage/jiayichen.jpg","陈嘉仪")
AddFace("http://huangjieqi.gitee.io/picture_storage/kg2000.jpg","徐旖芊")
AddFace("http://huangjieqi.gitee.io/picture_storage/liuxinrujiayou.jpg","刘心如")
AddFace("http://huangjieqi.gitee.io/picture_storage/liuyu19.png","刘宇")
AddFace("http://huangjieqi.gitee.io/picture_storage/ltco.jpg","李婷")
AddFace("http://huangjieqi.gitee.io/picture_storage/lucaszy.jpg","黄智毅")
AddFace("http://huangjieqi.gitee.io/picture_storage/pingzi0211.jpg","黄慧文")
AddFace("http://huangjieqi.gitee.io/picture_storage/shmimy-cn.jpg","张铭睿")
AddFace("http://huangjieqi.gitee.io/picture_storage/yichenting.jpg","陈婷")
AddFace("http://huangjieqi.gitee.io/picture_storage/coco022.jpg","洪可凡")
AddFace("http://huangjieqi.gitee.io/picture_storage/lujizhi.png","卢继志")
AddFace("http://huangjieqi.gitee.io/picture_storage/zzlhyy.jpg","张梓乐")

# 5.检测人脸
face_api_url = 'https://chick.cognitiveservices.azure.com/face/v1.0/detect'

# 请求正文
image_url = 'https://pic3.zhimg.com/v2-ad22f53d179d317b0195fe824874e6d4_r.jpg'

headers = {'Ocp-Apim-Subscription-Key': subscription_key}

# 请求参数
params = {
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    'recognitionModel':'recognition_03',#此参数需与facelist参数一致
    'detectionModel':'detection_01',
# 可选参数,请仔细阅读API文档
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair',
}

response = requests.post(face_api_url, params=params,
                         headers=headers, json={"url": image_url})
# json.dumps 将json--->字符串
response.json()

#运行结果
[{'faceId': '8502b63b-c45d-41c7-acdb-1b3ec4764c0e',
  'faceRectangle': {'top': 503, 'left': 490, 'width': 443, 'height': 443},
  'faceAttributes': {'smile': 0.0,
   'headPose': {'pitch': 3.9, 'roll': 5.7, 'yaw': 22.9},
   'gender': 'male',
   'age': 21.0,
   'facialHair': {'moustache': 0.1, 'beard': 0.1, 'sideburns': 0.1},
   'glasses': 'NoGlasses',
   'emotion': {'anger': 0.0,
    'contempt': 0.006,
    'disgust': 0.0,
    'fear': 0.0,
    'happiness': 0.0,
    'neutral': 0.834,
    'sadness': 0.159,
    'surprise': 0.0},
   'hair': {'bald': 0.02,
    'invisible': False,
    'hairColor': [{'color': 'brown', 'confidence': 0.99},
     {'color': 'black', 'confidence': 0.97},
     {'color': 'gray', 'confidence': 0.24},
     {'color': 'other', 'confidence': 0.1},
     {'color': 'blond', 'confidence': 0.09},
     {'color': 'red', 'confidence': 0.08},
     {'color': 'white', 'confidence': 0.0}]}}}]
findsimilars_url = "https://chick.cognitiveservices.azure.com/face/v1.0/findsimilars"


# 6.返回人脸相似置信度
findsimilars_url = "https://chick.cognitiveservices.azure.com/face/v1.0/findsimilars"

# 请求正文 faceId需要先检测一张照片获取
data_findsimilars = {
    "faceId":"65109723-281a-4e9b-abfd-6ade9722bda7",#取上方的faceID
    "faceListId": "chick_22",
#     "faceIds":faceId_02,
    "maxNumOfCandidatesReturned": 10,
    "mode": "matchFace"#matchPerson #一种为验证模式，一种为相似值模式
    }

r_findsimilars = requests.post(findsimilars_url,headers=headers,json=data_findsimilars)
# r_findsimilars
# <Response [200]>
# r_findsimilars.json()
[{'persistedFaceId': 'f2113ad2-cce9-4cb5-887b-52441ac4d7e9',
  'confidence': 1.0},
 {'persistedFaceId': '35c6ff4c-d882-4889-866f-cd4d1904899b',
  'confidence': 0.14134}]
  
# 用Pandas简化数据
import pandas as pd
# 返回facelist数据
faceListId_df = pd.json_normalize(r_get_facelist.json()["persistedFaces"])# 升级pandas才能运行
faceListId_df


# 返回相似度的数据
find_df = pd.json_normalize(r_findsimilars.json())# 升级pandas才能运行
find_df




# face++

# 1.准备工作——输入secret、key
api_secret = "LRKFaXunPufsYXtiBmlBctExAjFdxOy4"
api_key = 'rClGzsY-jCBauo7MwxBy7LtlmxAtC4Li' 

# 2.面部检测
import requests                                                        #调用 requests
api_secret = "LRKFaXunPufsYXtiBmlBctExAjFdxOy4"                        #填入从face++获得的api_secret
api_key = 'rClGzsY-jCBauo7MwxBy7LtlmxAtC4Li'                          #填入从face++上获得的api密钥
Detect_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect' 
img_url = 'https://pic3.zhimg.com/v2-ad22f53d179d317b0195fe824874e6d4_r.jpg' #填入想要检测的图片

payload = {
    "image_url":img_url,
    'api_key': api_key,
    'api_secret': api_secret,
    'return_attributes':'gender,age,smiling,emotion',                #输入要检测的人脸的特征
}
# r = requests.post(Detect_url,params=payload) 发送请求
# r.status_code 返回状态码
# 200
# r.json() 转义
{'request_id': '1603506906,83ce5f6f-45a3-438d-82d4-e6f05fb3177d',
 'time_used': 639,
 'faces': [{'face_token': '9b958e836855cf534be848bf36e4ff8e',
   'face_rectangle': {'top': 525, 'left': 414, 'width': 466, 'height': 466},
   'attributes': {'gender': {'value': 'Male'},
    'age': {'value': 18},
    'smile': {'value': 0.175, 'threshold': 50.0},
    'emotion': {'anger': 0.012,
     'disgust': 0.003,
     'fear': 0.003,
     'happiness': 0.003,
     'neutral': 96.584,
     'sadness': 3.394,
     'surprise': 0.003}}}],
 'image_id': 'p0jl9ISg6FjSqeoGrqTNAg==',
 'face_num': 1}
 
# 3.创建人脸集合
import requests,json

api_secret = "72ZSxF3jN4mKki4f6kcTCDIjlEvcwi4S"
api_key = 'n5iuIaeoc-HEqvbWSEMxc73zfy092FdR'  

display_name = "人脸集合"
outer_id = "jiji"
user_data = "相册集"

CreateFace_Url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create"
payload = {
    'api_key': api_key,
    'api_secret': api_secret,
    'display_name':display_name,
    'outer_id':outer_id,
    'user_data':user_data
}
# r = requests.post(CreateFace_Url, params=payload)
# r.json()
{'faceset_token': 'a761ef65cdc9fe38536cab5d2810e59b',
 'time_used': 125,
 'face_count': 0,
 'face_added': 0,
 'request_id': '1603509102,12202325-28ff-4390-8757-4963570858f6',
 'outer_id': 'jiji',
 'failure_detail': []}
 
# 4.获取人脸集合信息
GetDetail_Url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/getdetail"

payload = {
    'api_key': api_key,
    'api_secret': api_secret,
    'outer_id':outer_id,
}
 # r = requests.post(GetDetail_Url,params=payload)
 # r.json() 
 
{'faceset_token': 'a761ef65cdc9fe38536cab5d2810e59b',
 'tags': '',
 'time_used': 96,
 'user_data': '相册集',
 'display_name': '人脸集合',
 'face_tokens': [],
 'face_count': 0,
 'request_id': '1603509107,3737a5c0-81a9-4658-8264-314dfe6bb55b',
 'outer_id': 'jiji'} 
 
 # 5.增加人脸信息
 AddFace_url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/addface"

payload = {
    'api_key': api_key,
    'api_secret': api_secret,
    'faceset_token':'a761ef65cdc9fe38536cab5d2810e59b',  #选取上面面部结合的faceset_token
     'face_tokens':'2321c851d3177662945676f69131bc0b',    #选取面部识别的第一张face—_tokens
}

# r = requests.post(AddFace_url,params=payload)
# r.json()
{'faceset_token': 'a761ef65cdc9fe38536cab5d2810e59b',
 'time_used': 60,
 'face_count': 0,
 'face_added': 0,
 'request_id': '1603509165,ea1a1d8d-9573-4dda-8603-88bf10cf95de',
 'outer_id': 'jiji',
 'failure_detail': []}
 
 # 6.对比人脸相似度
 # 准备工作——输入人脸url
zhangxinchen01 = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=737410077,448616383&fm=26&gp=0.jpg"
zhangxinchen02 = "https://pic3.zhimg.com/v2-ad22f53d179d317b0195fe824874e6d4_r.jpg"
yiyangqianxi = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=119975422,485968842&fm=26&gp=0.jpg"
# 直接对比
Compare_url = "https://api-cn.faceplusplus.com/facepp/v3/compare"

payload ={
    'api_key': api_key,
    'api_secret': api_secret,
    'image_url1':zhangxinchen01, #人脸1
    'image_url2':yiyangqianxi,   #人脸2     
}
# r = requests.post(Compare_url,params=payload)
# r.json()
{'faces1': [{'face_rectangle': {'width': 101,
    'top': 60,
    'left': 257,
    'height': 101},
   'face_token': 'd9a97bebb3d4730fb6a1c7fc8ea9d2f0'}],
 'faces2': [{'face_rectangle': {'width': 115,
    'top': 116,
    'left': 187,
    'height': 115},
   'face_token': 'fca034b711b33f18a4008e1a10a68f23'}],
 'time_used': 739,
 'thresholds': {'1e-3': 62.327, '1e-5': 73.975, '1e-4': 69.101},
 'confidence': 58.853,
 'image_id2': 'Ozlbo+0qv7QL5DhJd0bVBg==',
 'image_id1': 'Y8n7mV4jaK+wvVNQjWJtDg==',
 'request_id': '1603510121,a4d79ff0-8d99-452d-a6c0-77571b89b263'}


 # 百度智能云人脸识别


 # 1.人脸检测

 # client_id 为官网获取的API Key， client_secret 为官网获取的Secret Key
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'
client_id = "4m6ZnsBPH2fRSG5KM87aXWGX"
client_secret = "cgEyCf1c8vaE77UtFyPpYyBxcnklpAXP"
response = requests.get(host.format(client_id, client_secret))
if response:
    print(response.json())
    
# 运行结果
{'refresh_token': '25.9b5dfe76495ae89c103b1c30d44bf1c0.315360000.1918889047.282335-22869614', 'expires_in': 2592000, 'session_key': '9mzdCrXg0mhDD0GFQMh26g9bl1QWf3fHkBhVO50Mujx5eSAsY13Rlqv18zGIHmrsYTvpIiZTqsv6xUJFS1b2LHwpg4Hhnw==', 'access_token': '24.11621453811871ffd5090281b1abfdb7.2592000.1606121047.282335-22869614', 'scope': 'public brain_all_scope vis-faceverify_faceverify_h5-face-liveness vis-faceverify_FACE_V3 vis-faceverify_idl_face_merge vis-faceverify_FACE_EFFECT vis-faceverify_face_feature_sdk wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component', 'session_secret': '9b188db970a3bd9933fec9592ada43b4'}

# 再次输入
access_token = '24.11621453811871ffd5090281b1abfdb7.2592000.1606121047.282335-22869614'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
if response:
    print (response.json())

# 获得
{'error_code': 222200, 'error_msg': 'request body should be json format', 'log_id': 7555752599840, 'timestamp': 1603531423, 'cached': 0, 'result': None
 
# 2.人脸对比
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"

params = "[{\"image\": \"https://pic3.zhimg.com/v2-ad22f53d179d317b0195fe824874e6d4_r.jpg\", \"image_type\": \"URL\", \"face_type\": \"CERT\", \"quality_control\": \"LOW\"}, {\"image\": \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603015508446&di=eee4e2c852d804bc3b80a719df3df9ef&imgtype=0&src=http%3A%2F%2Fimg2-cloud.itouchtv.cn%2Ftvtouchtv%2Fimage%2F20170914%2F1505363583630378.jpg\", \"image_type\": \"URL\", \"face_type\": \"LIVE\", \"quality_control\": \"LOW\"}]"
access_token = '24.11621453811871ffd5090281b1abfdb7.2592000.1606121047.282335-22869614' # 调用鉴权接口获取的token
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
response.json()

# 运行结果
{'error_code': 0,
 'error_msg': 'SUCCESS',
 'log_id': 7965158435997,
 'timestamp': 1603529425,
 'cached': 0,
 'result': {'score': 38.45040894,
  'face_list': [{'face_token': '12b008a071b14628fef340b2911da435'},
   {'face_token': '93d2501e1cb1685c26107d0b19cc854a'}]}}
   
# 3.创建用户组
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/add"

params = "{\"group_id\":\"group2\"}"
access_token = '24.11621453811871ffd5090281b1abfdb7.2592000.1606121047.282335-22869614' # 调用鉴权接口获取的token
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
response.json()

# 运行结果
{'error_code': 0,
 'error_msg': 'SUCCESS',
 'log_id': 9975256525201,
 'timestamp': 1603529483,
 'cached': 0,
 'result': None}
 
# 4.人脸注册
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add"

params = "{\"image\":\"91cf0a5aa45b0371989e56760b30548c\",\"image_type\":\"FACE_TOKEN\",\"group_id\":\"group1\",\"user_id\":\"user1\",\"user_info\":\"abc\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}"
access_token = '24.11621453811871ffd5090281b1abfdb7.2592000.1606121047.282335-22869614' # 调用鉴权接口获取的token
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
response.json()

# 运行结果
{'error_code': 0,
 'error_msg': 'SUCCESS',
 'log_id': 6599001351535,
 'timestamp': 1603529564,
 'cached': 0,
 'result': {'face_token': '91cf0a5aa45b0371989e56760b30548c',
  'location': {'left': 186.93,
   'top': 99.21,
   'width': 121,
   'height': 118,
   'rotation': 1}}}
   
 # 5.获取用户人脸列表
 request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/getlist"

params = "{\"user_id\":\"user1\",\"group_id\":\"group2\"}"
access_token = '24.11621453811871ffd5090281b1abfdb7.2592000.1606121047.282335-22869614' # 调用鉴权接口获取的token
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
response.json()

# 运行结果
{'error_code': 0,
 'error_msg': 'SUCCESS',
 'log_id': 6575750019489,
 'timestamp': 1603530412,
 'cached': 0,
 'result': {'face_list': [{'face_token': '91cf0a5aa45b0371989e56760b30548c',
    'ctime': '2020-10-23 17:46:47'}]}}

# 5.删除用户组
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/delete"

params = "{\"group_id\":\"group1\"}"
access_token = '24.11621453811871ffd5090281b1abfdb7.2592000.1606121047.282335-22869614' # 调用鉴权接口获取的token
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
response.json()

# 运行结果
{'error_code': 0,
 'error_msg': 'SUCCESS',
 'log_id': 7945001848415,
 'timestamp': 1603540838,
 'cached': 0,
 'result': None}